/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controle_visao;

import dao.ApoiadorDAO;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Apoiador;

/**
 *
 * @author Aluno
 */
public class FRMApoiador extends javax.swing.JFrame {

    /**
     * Creates new form Apoiador
     */
    public FRMApoiador() {
        
        initComponents();
        
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FRMApoiador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FRMApoiador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FRMApoiador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FRMApoiador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FRMApoiador().setVisible(true);
            }
        });
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        ApoCadastrar = new javax.swing.JButton();
        ApoAlterar = new javax.swing.JButton();
        ApoConsultar = new javax.swing.JButton();
        ApoExcuir = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jLabel1.setText("nome");

        jLabel2.setText("cnpj");

        jLabel3.setText("telefone");

        ApoCadastrar.setText("cadastrar");
        ApoCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ApoCadastrarActionPerformed(evt);
            }
        });

        ApoAlterar.setText("alterar");
        ApoAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ApoAlterarActionPerformed(evt);
            }
        });

        ApoConsultar.setText("consultar");
        ApoConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ApoConsultarActionPerformed(evt);
            }
        });

        ApoExcuir.setText("excluir");
        ApoExcuir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ApoExcuirActionPerformed(evt);
            }
        });

        jLabel4.setText("APOIADOR");

        jLabel5.setText("id");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "nome", "cnpj", "telefone", "id"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(72, 72, 72)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel5))
                                .addGap(28, 28, 28)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
                                    .addComponent(jTextField1)
                                    .addComponent(jTextField2)
                                    .addComponent(jTextField4)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(80, 80, 80)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(ApoConsultar)
                                    .addComponent(ApoCadastrar))
                                .addGap(63, 63, 63)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(ApoAlterar)
                                    .addComponent(ApoExcuir)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(166, 166, 166)
                                .addComponent(jLabel4)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ApoCadastrar)
                    .addComponent(ApoAlterar))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ApoExcuir)
                    .addComponent(ApoConsultar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ApoConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ApoConsultarActionPerformed
       if(jTextField1.getText().isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "Nome inválido!");
       }else{
           ArrayList <Apoiador> apoiador = apodao.consultar();
           if(apoiador.isEmpty()){
              JOptionPane.showMessageDialog(rootPane, "apoiador não está cadastrado.");  
           }else{
                excluirLinhasNaTabela(); //excluir linhas na tabela atual
                incluirLinhasNaTabela(apoiador); //incluir linhas na tabela para que elas possam receber os dados da consulta atual
                preencherTabela(apoiador);
           }
           
       }
           
    }//GEN-LAST:event_ApoConsultarActionPerformed

    private void ApoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ApoCadastrarActionPerformed
       apo.setNome(jTextField1.getText());
       apo.setCnpj(jTextField2.getText());
       apo.setTelefone(jTextField3.getText());
       apo.setId_apoio(Integer.parseInt(jTextField4.getText()));
       apodao.inserir(apo);
        
        
    }//GEN-LAST:event_ApoCadastrarActionPerformed

    private void ApoAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ApoAlterarActionPerformed
     if(jTextField1.getText().isEmpty() || jTextField2.getText().isEmpty() || jTextField3.getText().isEmpty() || jTextField4.getText().isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "Preencha todos os campos do formulário para alterar.");
     }else{
         if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que quer alterar o apoiador?") == 0){
             apodao.alterar(apo);
             ArrayList<Apoiador>apoiador;
             apodao.listar();
             excluirLinhasNaTabela(); //excluir linhas na tabela atual
            incluirLinhasNaTabela(null); //incluir linhas na tabela para que elas possam receber os dados da consulta atual
            preencherTabela(null);
             
         }
     }
        
    }//GEN-LAST:event_ApoAlterarActionPerformed

    private void ApoExcuirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ApoExcuirActionPerformed
       String id_apoio = jTextField4.getText();
        if(id_apoio.isEmpty())
             JOptionPane.showMessageDialog(rootPane, "Você deve escolher um apoiador para excluí-lo.");
         else{
            if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que quer excluir o apoiador") == 0){
           apodao.excluir(Integer.parseInt(id_apoio));
           ArrayList <Apoiador> apoiador ;
           apoiador = apodao.listar();
                
            }
        }
    }//GEN-LAST:event_ApoExcuirActionPerformed
    private void excluirLinhasNaTabela(){
        int qdeDeLinhas = jtbConsultaModel.getRowCount(); //a quantidade de linhas deve ser obtida antes de removê-las
        for (int cont=0; cont < qdeDeLinhas; cont++){ //sempre utilize a técnica de controle por contador e utilize como limite a quantidade de linhas presente na tabela (antes da remoção) 
            jtbConsultaModel.removeRow(0); //sempre remova a linha ZERO
        }
    }
    private void incluirLinhasNaTabela(ArrayList<Apoiador> apoiador){
        Object[] linha = new Object[6]; //cria um array de objetos com o tamanho da quantidade de campos (colunas) da tabela
        for(int c=0; c < apoiador.size(); c++){
            jtbConsultaModel.addRow(linha); //adiciona linhas na tabela até o tamanho do arrayList (que contém os dados de uma consulta do tipo listar)
        }
    }
     private void preencherTabela(ArrayList<Apoiador> apoiador){
        //adiciona os valores da consulta nas linhas da tabela
        int row = 0;        
        for (Apoiador apoio : apoiador) { //usa um for-each para percorrer o arrayList e alimentar a camada de modelo da JTable 
            jtbConsultaModel.setValueAt(apoio.getNome(),row ,0);
            jtbConsultaModel.setValueAt(apoio.getCnpj(),row,1);
            jtbConsultaModel.setValueAt(apoio.getTelefone(),row,2);
            jtbConsultaModel.setValueAt(apoio.getId_apoio(),row,3);
            row++;
        }  
    }
    
    
    
    
    /**
     * @param args the command line arguments
     */
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ApoAlterar;
    private javax.swing.JButton ApoCadastrar;
    private javax.swing.JButton ApoConsultar;
    private javax.swing.JButton ApoExcuir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
  
    modelo.Apoiador apo = new modelo.Apoiador();
    ApoiadorDAO apodao = new ApoiadorDAO();
    DefaultTableModel jtbConsultaModel;

}

